{#if published}
<p>{@html __('publish / republish-intro') }</p>
{:else}
<p style="margin-bottom: 20px">{@html __('publish / publish-intro') }</p>
{/if}

<button disabled="{ publishing }" on:click="publish()" class="btn-publish btn btn-primary btn-large {published?'':'btn-first-publish'}">
    {#if published}
    <span class="re-publish"
        ><i class="fa fa-fw fa-refresh {publishing ? 'fa-spin' : ''}"></i> <span class="title">{ __('publish / republish-btn') }</span></span
    >
    {:else}
    <span class="publish"
        ><i class="fa fa-fw {publishing ? 'fa-refresh fa-spin' : 'fa-cloud-upload'}"></i>
        <span class="title">{ __('publish / publish-btn') }</span></span
    >
    {/if}
</button>

{#if !published}
<div class="publish-intro">
    <div class="arrow">
        <i class="fa fa-chevron-left"></i>
    </div>
    <div class="text">
        {@html __('publish / publish-btn-intro') }
    </div>
</div>
{/if} {#if needs_republish && !publishing}
<div class="btn-aside alert">
    {@html __('publish / republish-alert') }
</div>
{/if} {#if published && !needs_republish && progress === 1 && !publishing}
<div class="alert alert-success">
    {@html __('publish / publish-success') }
</div>
{/if} {#if publish_error}
<div class="alert alert-error">
    {@html publish_error }
</div>
{/if} {#if publishing}
<div class="alert {progress < 1 ? 'alert-info' : 'alert-success'} publishing">
    { __("publish / progress / please-wait") }
    <div class="progress progress-striped active">
        <div class="bar {progress < 1 ? '' : 'bar-success'}" ref:bar />
    </div>
</div>
{/if}

<div style="margin-top:20px" class="{published?'':'inactive'}">
    <h2>{@html __('publish / share-embed') }</h2>
    <div class="block">
        <i class="icon fa fa-link fa-fw"></i>
        <div class="ctrls">
            <div class="h">
                <b>{@html __('publish / share-url') }</b>
                <div class="embed-options">
                    <label class="radio">
                        <input bind:group="shareurl_type" value="default" type="radio" name="url-type" />
                        {@html __('publish / share-url / fullscreen') }
                    </label>
                    {#each plugin_shareurls as tpl}
                    <label class="radio"> <input bind:group="shareurl_type" value="{tpl.id}" type="radio" name="url-type" /> {@html tpl.name} </label>
                    {/each}
                </div>
            </div>
            <div class="inpt">
                <a target="_blank" class="share-url" href="{shareUrl}">{shareUrl}</a>
            </div>
        </div>
        <Help>
            <div>{@html __('publish / help / share-url') }</div>
        </Help>
    </div>

    <div class="block">
        <i class="icon fa fa-code fa-fw"></i>
        <div class="ctrls">
            <div class="h">
                <b>{@html __('publish / embed') }</b>
                <div class="embed-options">
                    {#each embed_templates as tpl}
                    <label class="radio"><input type="radio" bind:group="embed_type" value="{tpl.id}" /> {@html tpl.title }</label>
                    {/each}
                </div>
            </div>
            <div class="inpt">
                <input ref:embedInput type="text" class="input embed-code" readonly value="{embedCode}" />
                <button class="btn btn-copy" on:click="copy(embedCode)" title="copy"><i class="fa fa-copy"></i> { __('publish / copy') }</button>
                <div class="copy-success {copy_success ? 'show':''}">
                    { __('publish / copy-success') }
                </div>
            </div>
        </div>
        <Help>
            <div>
                {@html __('publish / embed / help') } {#each embed_templates.slice(2) as tpl}
                <div><b>{tpl.title}:</b> {@html tpl.text}</div>
                {/each}
            </div>
        </Help>
    </div>
</div>

<style>
    .btn-publish {
        border-color: #1d81a2 !important;
        box-shadow: 0px 3px 6px rgba(0, 0, 0, 0.25);
        line-height: 20px;
        padding: 15px;
    }

    .btn-first-publish {
        text-align: center;
        width: 150px;
        vertical-align: middle;
        padding: 15px 0 15px;
    }

    .btn-publish i.fa {
        font-size: 20px;
    }
    .btn-first-publish i.fa {
        font-size: 32px;
        display: block;
        margin: 5px auto;
    }

    .btn-first-publish .title {
        display: block;
        text-align: center;
        font-size: 18px;
        line-height: 22px;
        padding: 5px 20px 0px 20px;
    }
    .publish-intro {
        display: inline-block;
        font-size: 18px !important;
        line-height: 22px;
    }

    .publish-intro .arrow {
        vertical-align: middle;
        display: inline-block;
        padding: 15px;
    }
    .publish-intro .text {
        vertical-align: middle;
        display: inline-block;
        width: 200px;
    }
    @media (max-width: 1200px) {
        .publish-intro {
            font-size: 15px;
        }
        .publish-intro .text {
            vertical-align: middle;
            display: inline-block;
            width: 140px;
            line-height: 18px;
            font-size: 15px;
        }
    }

    div.progress {
        margin-top: 8px;
        margin-bottom: 4px;
    }
    input[type='radio'] {
        vertical-align: baseline !important;
    }
    a.share-url {
        font-size: 18px;
    }
    .btn-aside.alert {
        margin-left: 0;
        margin-top: 7px;
        max-width: 100%;
    }

    .copy-success {
        font-size: 11px;
        color: #9c9;
        font-style: italic;
        opacity: 0;
        pointer-events: none;
        transition: opacity 5s ease-in;
        margin-top: -10px;
        position: absolute;
    }
    .copy-success.show {
        opacity: 1;
        transition: none;
    }
    .embed-options {
        display: inline-block;
    }
</style>

<script>
    /* eslint camelcase: "off" */
    import Help from '../editor/Help.html';

    import { __ } from '../shared/l10n';
    import { trackEvent } from '../shared/analytics';
    import { getJSON, postJSON } from '../shared/utils';
    import computeEmbedHeights from './compute-embed-heights';

    let fakeProgress = 0;
    let initial_auto_publish = true;

    export default {
        components: { Help },
        data() {
            return {
                chart: {
                    id: ''
                },
                embed_templates: [],
                plugin_shareurls: [],
                published: false,
                publishing: false,
                needs_republish: false,
                publish_error: false,
                auto_publish: false,
                progress: 0,
                shareurl_type: 'default',
                embed_type: 'responsive',
                copy_success: false
            };
        },

        computed: {
            shareUrl({ shareurl_type, chart, plugin_shareurls, published }) {
                if (!published) return 'https://www.datawrapper.de/...';
                if (shareurl_type === 'default') return chart.publicUrl;
                let url = '';
                plugin_shareurls.forEach(t => {
                    if (t.id === shareurl_type) url = t.url.replace(/%chart_id%/g, chart.id);
                });
                return url;
            },

            embedCode({ embed_type, chart }) {
                if (!chart.metadata) return '';
                if (chart.metadata.publish && !chart.metadata.publish['embed-codes'])
                    return `<iframe src="${chart.publicUrl}" width="100%" height="${
                        chart.metadata.publish['embed-height']
                    }" scrolling="no" frameborder="0" allowtransparency="true"></iframe>`;
                return chart.metadata.publish['embed-codes']['embed-method-' + embed_type];
            }
        },
        helpers: { __ },
        methods: {
            publish() {
                const me = this;
                // wait another 100ms until the page is ready
                if (!window.chart.save) {
                    setTimeout(() => {
                        me.publish();
                    }, 100);
                    return;
                }
                const { chart } = me.get();

                me.set({
                    publishing: true,
                    progress: 0,
                    publish_error: false
                });
                // generate embed codes
                chart.metadata.publish['embed-heights'] = computeEmbedHeights(chart, me.get().embed_templates);

                // update charts
                me.set({ chart });
                // save embed heights and wait until it's done before
                // we start to publish the chart
                trackEvent('Chart Editor', 'publish');

                window.chart
                    .attributes(chart)
                    .save()
                    .then(d => {
                        // publish chart
                        postJSON(`/api/charts/${chart.id}/publish`, null, res => {
                            if (res.status === 'ok') {
                                trackEvent('Chart Editor', 'publish-success');
                                me.publishFinished(res.data);
                            } else {
                                trackEvent('Chart Editor', 'publish-error', res.message);
                                me.set({ publish_error: res.message });
                            }
                        });
                        fakeProgress = 0;
                        me.updateStatus();
                    });
            },

            updateProgressBar(p) {
                if (this.refs.bar) {
                    this.refs.bar.style.width = (p * 100).toFixed() + '%';
                }
            },

            updateStatus() {
                const me = this;
                const { chart } = me.get();
                fakeProgress += 0.05;
                getJSON(`/api/charts/${chart.id}/publish/status`, res => {
                    if (res) {
                        res = +res / 100 + fakeProgress;
                        me.set({ progress: Math.min(1, res) });
                    }
                    if (me.get().publishing) {
                        setTimeout(() => {
                            me.updateStatus();
                        }, 400);
                    }
                });
            },

            publishFinished(chartInfo) {
                this.set({
                    progress: 1,
                    published: true,
                    needs_republish: false
                });
                setTimeout(() => this.set({ publishing: false }), 500);
                this.set({ chart: chartInfo });

                if (window.parent) {
                    window.parent.postMessage(
                        {
                            source: 'datawrapper',
                            type: 'chart-publish',
                            chartId: chartInfo.id
                        },
                        '*'
                    );
                }

                window.chart.attributes(chartInfo);
            },

            copy(embedCode) {
                const me = this;
                me.refs.embedInput.select();
                try {
                    var successful = document.execCommand('copy');
                    if (successful) {
                        trackEvent('Chart Editor', 'embedcode-copy');
                        me.set({ copy_success: true });
                        setTimeout(() => me.set({ copy_success: false }), 300);
                    }
                } catch (err) {
                    // console.log('Oops, unable to copy');
                }
            }
        },
        onstate({ changed, current }) {
            const userDataReady = window.dw && window.dw.backend && window.dw.backend.setUserData;
            if (changed.publishing) {
                if (current.publishing) this.updateProgressBar(current.progress);
            }
            if (changed.progress) {
                this.updateProgressBar(current.progress);
            }
            if (changed.embed_type && userDataReady) {
                const data = window.dw.backend.__userData;
                if (!current.embed_type || !data) return;
                data.embed_type = current.embed_type;
                window.dw.backend.setUserData(data);
            }
            if (changed.shareurl_type && userDataReady) {
                const data = window.dw.backend.__userData;
                if (!current.shareurl_type || !data) return;
                data.shareurl_type = current.shareurl_type;
                window.dw.backend.setUserData(data);
            }
            if (changed.published) {
                window.document.querySelector('.dw-create-publish .publish-step').classList[current.published ? 'add' : 'remove']('is-published');
            }
            if (changed.auto_publish) {
                if (current.auto_publish && initial_auto_publish) {
                    this.publish();
                    initial_auto_publish = false;
                    window.history.replaceState('', '', window.location.pathname);
                }
            }
        }
    };
</script>
